package com.handpay.zztong.hp.main.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.utils.ArithUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.QRCodeReceiptActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ScanQrCodeActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Address;
import com.handpay.zztong.hp.bean.Rate;
import com.handpay.zztong.hp.bean.Rates;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.main.model.AvailableTradeType;
import com.handpay.zztong.hp.main.model.LowestAccountTransferAmount;
import com.handpay.zztong.hp.main.model.QueryCertNoExpiryDateBean;
import com.handpay.zztong.hp.main.model.RateList;
import com.handpay.zztong.hp.main.model.TradeAreaBean;
import com.handpay.zztong.hp.main.widget.RateDialogFragment;
import com.handpay.zztong.hp.nocardpay.activity.NoCardPayActivity;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.qualification.activity.IDCardateActivity;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.math.BigDecimal;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import se.krka.kahlua.vm.LuaTable;

import static com.handpay.zztong.hp.bean.Address.areaRadius;

@SuppressLint("NewApi")
public class ReceivablesFragment extends BaseFragment implements View.OnClickListener, RateDialogFragment.OnRateViewButtonLinsener {

    private static final String TAG = "ReceivablesFragment";
    protected TextView mInputMoneyet;
    /**
     * 记录当前输入金额的字符串。通过CommonUtils.formatMoney设置到mInputMoneyet
     */
    private String mMoneyText;
    private View receivablesLayout;
    private String webTitle = null;
    private String webUrl = null;
    private int isOpen = 1;
    /***
     * 支付宝支付
     */
    public static int PAY_TYPE_ALIPAY = 2;
    /***
     * 微信支付
     */
    public static int PAY_TYPE_WECHATPAY = 3;
    public static int PAY_TYPE_WECHATPAY_SCANNER = 4;

    public boolean isOpenBank = true;           //刷卡支付是否打开
    public boolean isOpenAlipay = false;        //支付宝是否打开
    public boolean isOpenWechatPay = false;     //微信反扫是否打开
    public boolean isOpenWechatPayScan = false; //微信正扫是否打开
    public boolean isOpenAlipayScan = false;//支付宝正扫是否打开
    public boolean isOpenScannerPay = true;      //新版扫描码支付
    public boolean isOpenNoCardPay = false;     //无卡支付是否打开

//    public static boolean ISCLEARDATA = false;  // 是否清除数据 第三方支付成功返回的时候清除数据
    private Rate currentSelectRate = null;//当前选择的费率

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        receivablesLayout = inflater.inflate(R.layout.fragment_receivables, container, false);
        initView();
        getLowestAccountTransferAmount();
        if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            if (mCertNoExpiryDate == -1) {
                queryCardExpiryDate();
            }
        }
        return receivablesLayout;
    }

    /**
     * 获取证件信息是否过期
     */
    private void queryCardExpiryDate() {
        if (!checkMyActivityIsNull()) {
            Hashtable<String, String> params = new Hashtable<>();
            params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
            mainActivity.doJsonPost(true, mainActivity, ZZTongActivity.Do_QueryCertNoExpiryDate, QueryCertNoExpiryDateBean.class, params, true, true);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        //获取可用支付方式
        getTradeType();
        MainActivity.currFragTag = ZZTConstant.FRAGMENT_FLAG_RECEIVABLES;
        restZero();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private int amount = 0;// 银行卡最低收款额度
    private int wechatAmount = 0;// 微信反扫最低收款额度
    private int alipayAmount = 0;// 支付宝最低收款额度
    private int wechatScanpayAmount = 0;//微信正扫最低限额
    private int aliScanpayAmount = 0;//支付宝正扫最低额
    private Double selectAmount = 0d;
    private int scanpayAmount = 0;//扫码支付最低限额
    private int noCardPayAmount = 0;//无卡支付最低限额
    private Rates rates;

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert, OnClickListener on, boolean isDataCompile) {
        if (ZZTongActivity.Do_GetLowestAccountTransferAmount.equals(action)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//            amount = (Double) luaTable.rawget("amount");
//            wechatAmount = CommonUtils.objectToDouble(luaTable.rawget("wechatAmount"));
//            alipayAmount = CommonUtils.objectToDouble(luaTable.rawget("alipayAmount"));
//            wechatScanpayAmount = CommonUtils.objectToDouble(luaTable.rawget("wechatScanpayAmount"));
//            scanpayAmount = CommonUtils.objectToDouble(luaTable.rawget("scanpayAmount"));
            // 插入广发“慧存钱”的一个协议.
//            mainActivity.doPost(mainActivity, ZZTongActivity.Do_ZztAutoPaymentFinancingProduct, treatParams(), true);
            return true;
        } else if (ZZTongActivity.Do_ZztRateList.equals(action)) {
//            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
//            rates = Rates.generateRates(data, isDataCompile);
//            HPLog.e(HPLog.FDL_TAG, "rates.isRateNull()=====:" + rates.isRateNull());
//            if (!rates.isRateNull()) {
//                Intent it = new Intent(mainActivity, Muiltate.class);
//                it.putExtra("rates", rates);
//                it.putExtra("amount", selectAmount);
//                it.putExtra("isOpen", isOpen);
//                this.startActivity(it);
//                restZero();
//            } else {
//                onVPOS();
//            }
            return true;
        } else if (ZZTongActivity.Do_GetPhotoSwitch.equals(action)) {// 获取是否拍照开关
            isOpen = 1;
            LuaTable luaTable;
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                Object obj = luaTable.rawget("isOpen");
                if (obj instanceof Integer) {
                    isOpen = (Integer) obj;
                } else if (obj instanceof Double) {
                    double dObj = (Double) obj;
                    isOpen = (int) dObj;
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            getMuiltRate(selectAmount);
            return true;
        } else if (ZZTongActivity.Do_GetAreaTradeValue.equals(action)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                String locationLat = (String) luaTable.rawget("locationLat");
                String locationLng = (String) luaTable.rawget("locationLng");
                double areaRadius = (Double) luaTable.rawget("areaRadius");
                HPLog.i(HPLog.FDL_TAG, "locationLat = " + locationLat + "  locationLng= " + locationLng + " areaRadius=" + areaRadius);
                if (TextUtils.isEmpty(locationLat) || TextUtils.isEmpty(locationLng) || areaRadius <= 0) {
                    Address.reSetAddress();
                }
                Address.setAddress(Double.parseDouble(locationLat), Double.parseDouble(locationLng), areaRadius);
            } catch (Exception e) {
                e.printStackTrace();
                Address.reSetAddress();
            } finally {
                getMuiltRate(selectAmount);
            }
        } else if (action.equals(ZZTongActivity.DO_GetAvailableTradeType)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            LuaTable list = (LuaTable) luaTable.rawget("list");
            Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
            if (list != null) {
                for (LuaTable tradeTypeModle : dataList) {
                    Double isOpen = CommonUtils.objectToDouble(tradeTypeModle.rawget("isOpen"));
                    Double tradeType = CommonUtils.objectToDouble(tradeTypeModle.rawget("tradeType"));
                    int open = isOpen.intValue();
                    int type = tradeType.intValue();
                    if (open == 1 && type == 1) {
                        isOpenBank = true;
                    } else if (open == 1 && type == 2) {
                        isOpenAlipay = true;
                    } else if (open == 1 && type == 3) {
                        isOpenWechatPay = true;
                    } else if (open == 1 && type == 4) {
                        isOpenWechatPayScan = true;
                    } else if (open == 1 && type == 8) {
                        isOpenAlipayScan = true;
                    } else if (open == 1 && type == 5) {
                        isOpenScannerPay = true;
                    }
                }
                HPLog.i(HPLog.SSX_TAG, "isOpenBank:" + isOpenBank + "|isOpenAlipay:" + isOpenAlipay + "|isOpenWechatPay:" + isOpenWechatPay + "|isOpenWechatPayScan:" + isOpenWechatPayScan + "isOpenSannerPay:" + isOpenScannerPay);
            }
        } else if (action.equals(ZZTongActivity.Do_QrCodeTransfer)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            String qrCodeUrl = luaTable.rawget("qrCodeUrl").toString();
            HPLog.i(HPLog.SSX_TAG, "before Secure qrCodeUrl:" + qrCodeUrl);
            String mQrCodeUrl = SecureManager.getInstance().des(qrCodeUrl, 0, null);
            HPLog.i(HPLog.SSX_TAG, "after Secure mQrCodeUrl:" + mQrCodeUrl);
            String orderNo = luaTable.rawget("orderNo").toString();
            String token = luaTable.rawget("token").toString();
            String payOrderID = luaTable.rawget("payOrderID").toString();
            Intent intent = new Intent();
            intent.putExtra("mQrCodeUrl", mQrCodeUrl);
            intent.putExtra("mOrderNo", orderNo);
            intent.putExtra("amount", ArithUtil.mul(selectAmount, 100d));
            intent.putExtra("tradeType", PAY_TYPE_WECHATPAY_SCANNER);
            intent.putExtra("isOpenWechatPayScan", isOpenWechatPayScan);
            intent.putExtra("token", token);
            intent.putExtra("payOrderID", payOrderID);
            intent.setClass(mainActivity, ScanQrCodeActivity.class);
            startActivity(intent);
        } else if (action.equals(ZZTongActivity.Do_QueryCertNoExpiryDate)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            if (luaTable != null) {
                String status = String.valueOf(luaTable.rawget("status"));
                mCertNoExpiryDate = (!TextUtils.isEmpty(status)) ? Integer.valueOf(status) : -1;
                //-1无相关记录
                if (!TextUtils.isEmpty(status) && status.equals("01") || status.equals("03")) {
                    String tipmsg = String.valueOf(luaTable.rawget("remindMessage"));
                    if (mainActivity != null) {
                        mainActivity.showAlertDialog(mainActivity, mainActivity.getString(R.string.tip), tipmsg, false, "去提交", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent intent = new Intent(mainActivity, IDCardateActivity.class);
                                startActivity(intent);
                            }
                        }, "知道了", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, OnClickListener on) {
        if (super.netJsonResponse(action, resp, showAlert, on)) {
            return true;
        }
        if (ZZTongActivity.Do_GetLowestAccountTransferAmount.equals(action)) {
            LowestAccountTransferAmount lowestAccountTransferAmount = (LowestAccountTransferAmount) resp;
            amount = lowestAccountTransferAmount.getAmount();
            wechatAmount = lowestAccountTransferAmount.getWechatAmount();
            alipayAmount = lowestAccountTransferAmount.getAlipayAmount();
            wechatScanpayAmount = lowestAccountTransferAmount.getWechatScanpayAmount();
            aliScanpayAmount = lowestAccountTransferAmount.getAliScanpayAmount();
            scanpayAmount = lowestAccountTransferAmount.getScanpayAmount();
            noCardPayAmount = lowestAccountTransferAmount.getNoCardPayAmount();
            // 插入广发“慧存钱”的一个协议.
//            mainActivity.doPost(mainActivity, ZZTongActivity.Do_ZztAutoPaymentFinancingProduct, treatParams(), true);
            return true;
        } else if (ZZTongActivity.Do_ZztRateList.equals(action)) {
            RateList bean = (RateList) resp;
            rates = Rates.generateRates(bean);
//            rates=Rates.generateTestRates();
            HPLog.i(HPLog.TAG_RESULT, "rates.size：" + rates.getRates().size());
            if (!rates.isRateNull()) {
//                Intent it = new Intent(mainActivity, Muiltate.class);
//                it.putExtra("rates", rates);
//                it.putExtra("amount", selectAmount);
//                it.putExtra("isOpen", isOpen);
//                this.startActivity(it);
//                restZero();
                RateDialogFragment.newInstance(getString(R.string.hint_titile_rate), rates, true, this).show(getFragmentManager(), "rate");
            } else {
                onVPOS();
            }
            return true;
        } else if (action.equals(ZZTongActivity.DO_GetAvailableTradeType)) {
            AvailableTradeType bean = (AvailableTradeType) resp;
            List<AvailableTradeType.ListBean> dataList = bean.getList();
            if (dataList != null) {
                for (AvailableTradeType.ListBean tradeTypeModle : dataList) {
                    int open = CommonUtils.objectToInt(tradeTypeModle.getIsOpen());
                    int type = CommonUtils.objectToInt(tradeTypeModle.getTradeType());
                    if (type == 1) {
                        if (open == 1) {
                            isOpenBank = true;
                        } else {
                            isOpenBank = false;
                        }
                    } else if (type == 2) {
                        if (open == 1) {
                            isOpenAlipay = true;
                        } else {
                            isOpenAlipay = false;
                        }
                    } else if (type == 3) {
                        if (open == 1) {
                            isOpenWechatPay = true;
                        } else {
                            isOpenWechatPay = false;
                        }
                    } else if (type == 4) {
                        if (open == 1) {
                            isOpenWechatPayScan = true;
                        } else {
                            isOpenWechatPayScan = false;
                        }
                    } else if (type == 5) {
                        if (open == 1) {
                            isOpenScannerPay = true;
                        } else {
                            isOpenScannerPay = false;
                        }
                    } else if (type == 6) {
                        if (open == 1) {
                            isOpenNoCardPay = true;
                        } else {
                            isOpenNoCardPay = false;
                        }
                    } else if (type == 8) {
                        if (open == 1) {
                            isOpenAlipayScan = true;
                        } else {
                            isOpenAlipayScan = false;
                        }
                    }
                }
                HPLog.i(HPLog.SSX_TAG, "isOpenBank:" + isOpenBank + "|isOpenAlipay:" + isOpenAlipay + "|isOpenWechatPay:" + isOpenWechatPay + "|isOpenWechatPayScan:" + isOpenWechatPayScan + "isOpenAlipayScan:" + isOpenAlipayScan + "isOpenSannerPay:" + isOpenScannerPay);
            }
        } else if (action.equals(ZZTongActivity.Do_GetAreaTradeValue)) {
            TradeAreaBean tradeAreaBean = (TradeAreaBean) resp;
            HPLog.i(HPLog.FDL_TAG, "locationLat = " + tradeAreaBean.getLocationLat() + "  locationLng= " + tradeAreaBean.getLocationLng() + " areaRadius=" + tradeAreaBean.getAreaRadius());
            if (TextUtils.isEmpty(tradeAreaBean.getLocationLat()) || TextUtils.isEmpty(tradeAreaBean.getLocationLng()) || areaRadius <= 0) {
                Address.reSetAddress();
            } else {
                Address.setAddress(0.0d, 0.0d, 0.0d);
                Address.reSetAddress();
            }
            getMuiltRate(selectAmount);
        } else if (action.equals(ZZTongActivity.Do_QueryCertNoExpiryDate)) {
            QueryCertNoExpiryDateBean queryCertNoExpiryDateBean = (QueryCertNoExpiryDateBean) resp;
            mCertNoExpiryDate = (!TextUtils.isEmpty((queryCertNoExpiryDateBean.getStatus()))) ? CommonUtils.objectToInt(queryCertNoExpiryDateBean.getStatus()) : -1;
            //-1无相关记录
            if (!TextUtils.isEmpty(queryCertNoExpiryDateBean.getStatus()) && queryCertNoExpiryDateBean.getStatus().equals("01") || queryCertNoExpiryDateBean.getStatus().equals("03")) {
                String tipmsg = queryCertNoExpiryDateBean.getRemindMessage();
                if (mainActivity != null) {
                    mainActivity.showAlertDialog(mainActivity, mainActivity.getString(R.string.tip), tipmsg, false, mainActivity.getString(R.string.hint_goto_commit), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(mainActivity, IDCardateActivity.class);
                            startActivity(intent);
                        }
                    }, mainActivity.getString(R.string.hint_user_konw), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        }
        return false;
    }

    private View findViewById(int id) {
        return receivablesLayout.findViewById(id);
    }

    private void initView() {
//        boolean hasMenuKey = ViewConfiguration.get(mActivity).hasPermanentMenuKey();
//        if (!hasMenuKey) {
//            LinearLayout body_ll = (LinearLayout) findViewById(R.id.body_ll);
//            body_ll.setPadding(0, 50, 0, 50);
//        }
        mInputMoneyet = (TextView) findViewById(R.id.rf_tv_input_amount);
        mMoneyText = ZZTConstant.MONEY_ZERO;
        findViewById(R.id.rf_hpKbNum1).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum2).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum3).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum4).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum5).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum6).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum7).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum8).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum9).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum0).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum00).setOnClickListener(this);
        findViewById(R.id.rf_hpKbCancle).setOnClickListener(this);
        findViewById(R.id.rf_hpKbOk).setOnClickListener(this);
        findViewById(R.id.rf_hpKbDot).setOnClickListener(this);
//        findViewById(R.id.rf_wechat_btn).setOnClickListener(this);
//        findViewById(R.id.rf_no_card_pay_btn).setOnClickListener(this);

        findViewById(R.id.rf_hpKbCancle).setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                restZero();
                return true;
            }
        });
        restZero();
    }

    protected void restZero() {
        SpannableString msp = new SpannableString("¥0.00");
        msp.setSpan(new RelativeSizeSpan(0.7f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mMoneyText = ZZTConstant.MONEY_ZERO;
        mInputMoneyet.setText(msp);
//        ISCLEARDATA = false;
    }

    private void moneyText(String money) {
        mMoneyText = money;
        String temp_money = money;
        SpannableString msp = new SpannableString("¥" + CommonUtils.formatMoneyWithSplite(Double.parseDouble(temp_money)));
        msp.setSpan(new RelativeSizeSpan(0.7f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mInputMoneyet.setText(msp);
    }

    private String dealInput(char c) {
        String money = mMoneyText;
        // 如果输入删除
        if ('-' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money) || money.length() == 1) {
                return ZZTConstant.MONEY_ZERO;
            }
            if ('.' == money.charAt(money.length() - 1)) {
                if (2 == money.length()) {
                    return ZZTConstant.MONEY_ZERO;
                } else {
                    return money.substring(0, money.length() - 2);
                }
            }
            return money.substring(0, money.length() - 1);
        }

        int indexOfDot = money.indexOf(".");
        // 如果当前没有输入小数点，且要输入的不是小数点的时候
        if (-1 == indexOfDot && '.' != c) {
            if (money.length() >= ZZTConstant.MONEY_MAX_LEN) {
                return money;
            }
        }
        // 如果遇到输入0。注意输入00.相当于调用两次输入0
        if ('0' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return ZZTConstant.MONEY_ZERO;
            }
            // 如果没有小数点，或者没有输入到小数点后两位，仍然可以输入
            if (indexOfDot == -1 || indexOfDot >= (money.length() - 2)) {
                return money + c;
            }
        }
        // 如果遇到输入1~9
        if ('1' <= c && '9' >= c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return c + "";
            }
            // 如果没有小数点，或者没有输入到小数点后两位，仍然可以输入
            if (indexOfDot == -1 || indexOfDot >= (money.length() - 2)) {
                return money + c;
            }
        }
        // 如果遇到输入点
        if ('.' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return "0.";
            }
            // 如果当前money没有'.'
            if (!money.contains(".")) {
                return (money + ".");
            }
        }
        return money;
    }

    public void onClick(View v) {
        char c;
        int i = v.getId();
        if (i == R.id.rf_hpKbNum1) {
            c = '1';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum2) {
            c = '2';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum3) {
            c = '3';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum4) {
            c = '4';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum5) {
            c = '5';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum6) {
            c = '6';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum7) {
            c = '7';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum8) {
            c = '8';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum9) {
            c = '9';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum0) {
            c = '0';
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbNum00) {
            c = '0';
            moneyText(dealInput(c));
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbDot) {
            c = '.';
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbCancle) {
            c = '-';
            moneyText(dealInput(c));
        }

//        else if (i == R.id.rf_no_card_pay_btn) {
//            if (isOpenNoCardPay) {
//                if (AccountUtils.getAccountStatus(mActivity) != AccountUtils.AccountStatus.SUCCESS && AccountUtils.getAccountStatus(mActivity) != AccountUtils.AccountStatus.CHECKING) {
//                    mainActivity.showAlertDialog(mainActivity, getString(R.string.tip), getString(R.string.toast_need_tip1));
//                    return;
//                }
//                if (AndPermission.hasPermission(mainActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {
//                    HPLog.i(HPLog.YL_TAG, "rf_no_card_pay_btn:1");
//
//                    doOKClickNoCardPay();
//                } else {
//                    HPLog.i(HPLog.YL_TAG, "rf_no_card_pay_btn:2");
//
//                    AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_NO_CARD_PAY)
//                            .permission(Manifest.permission.ACCESS_FINE_LOCATION).rationale(new RationaleListener() {
//                        @Override
//                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
//                            HPLog.i(HPLog.YL_TAG, "rf_no_card_pay_btn:3");
//                            AndPermission.rationaleDialog(mainActivity, rationale).show();
//                        }
//                    }).send();
//                }
//            } else {
//
//                mainActivity.showAlertDialog(mainActivity, "", getString(R.string.hint_cannot_paytype), false);
//            }
//        }
//        else if (i == R.id.rf_wechat_btn) {
//            if (chekUserTimeout.isTimeOut()) {
//                goLoginWithTimeOut();
//                return;
//            }
//            /**
//             * 扫码支付
//             */
//            if (isOpenScannerPay) {
//                if (AccountUtils.getAccountStatus(mActivity) != AccountUtils.AccountStatus.SUCCESS) {
//                    mainActivity.showAlertDialog(mainActivity, getString(R.string.tip), getString(R.string.toast_need_tip1));
//                    return;
//                }
//                if (AndPermission.hasPermission(mainActivity,Manifest.permission.ACCESS_FINE_LOCATION)) {
//                    doOKClickWebPay();
//                } else {
//                    AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_WEBPAY).
//                            permission(Manifest.permission.ACCESS_FINE_LOCATION).
//                            rationale(new RationaleListener() {
//                                @Override
//                                public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
//                                    AndPermission.rationaleDialog(mainActivity, rationale).show();
//                                }
//                            }).send();
//                }
//
//            } else {
//                mainActivity.showAlertDialog(mainActivity, "", getString(R.string.hint_cannot_paytype), false);
//            }
//
//        }

        else if (i == R.id.rf_hpKbOk) {
            if (chekUserTimeout.isTimeOut()) {
                goLoginWithTimeOut();
                return;
            }
            if (isOpenBank) {
                if (AndPermission.hasPermission(mainActivity, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO)) {
                    doOKClickBankCardPay();
                } else {
                    AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY).
                            permission(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO).
                            rationale(new RationaleListener() {
                                @Override
                                public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                    AndPermission.rationaleDialog(mainActivity, rationale).show();
                                }
                            }).send();
                }

            } else {
                mainActivity.showAlertDialog(mainActivity, "", getString(R.string.hint_cannot_paytype), false);
            }

        }
    }

    @Override
    public String getFragmentTitle() {
        return ZZTConstant.FRAGMENT_FLAG_RECEIVABLES;
    }

    @Override
    public ActionBar getFragmentActionBar() {
        super.getFragmentActionBar();
        return new ActionBar(getFragmentTitle());
    }

    /***
     * 获取最低支持的金额
     */
    private void getLowestAccountTransferAmount() {
        if (!checkMyActivityIsNull()) {
            Hashtable<String, String> params = new Hashtable<String, String>();
            params.put("version", ClientEngine.VERSION);
            params.put("platform", ClientEngine.MOBILETYPE);
            params.put("channel", ClientEngine.CHANNEL);
            mainActivity.doJsonPost(true, mainActivity, ZZTongActivity.Do_GetLowestAccountTransferAmount, LowestAccountTransferAmount.class, params, true, true);
        }
    }

    /***
     * 获取交易方式
     */
    private void getTradeType() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        mainActivity.doJsonPost(true, mainActivity, ZZTongActivity.DO_GetAvailableTradeType, AvailableTradeType.class, params, false);
    }

    /***
     * 刷卡支付
     *
     * @return
     */
    protected boolean doOKClickBankCardPay() {
        if (checkMyActivityIsNull()) {
            return false;
        }
        if (!mainActivity.requestCurrentLocation(true)) {
            return false;
        }
        String content = mInputMoneyet.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return false;
        }
        selectAmount = Double.valueOf(mMoneyText);
        if ((selectAmount * 100) < amount) {
            Toast.makeText(mainActivity, getString(R.string.min_transfer_alert, Double.valueOf(amount) / 100), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {

            // 检查有没有插刷卡器 checkVPOS(this, true)
            if (mainActivity.checkVPOS(mainActivity, true)) {

                // 没有上传资质审核信息，提醒用户提交资质审核
                mainActivity.showAlertDialog(mainActivity, getString(R.string.tip), getString(R.string.QualificationsPromptVOP_2), true, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mainActivity.checkSwiperOk(mainActivity, true)) {
                            // GOTO 提交资质审核界面
                            startActivity(mainActivity.getComposeIntent());
                            dialog.dismiss();
                        }
                    }
                }, null);
            }
            return false;
        } else {
            HPLog.e(HPLog.FDL_TAG, "selectAmount:" + selectAmount);
            if (Address.IS_CHECK_ADDRESS) {
                getAreaTradeValue();
            } else {
                getMuiltRate(selectAmount);
            }
        }
        return true;
    }

    /***
     * 第三方支付(正扫)
     *
     */
    private void doOKClickWebPay() {
        if (!mainActivity.requestCurrentLocation(true)) {
            return;
        }
        String content = mInputMoneyet.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        selectAmount = Double.valueOf(mMoneyText);
        if (!isOpenWechatPayScan && !isOpenAlipayScan) {
            Toast.makeText(mainActivity, getString(R.string.hint_cannot_paytype), Toast.LENGTH_SHORT).show();
        }
        selectPayType();
         /*SwiperUtils.cleanSwiperData();
        double minAmount = scanpayAmount;//扫码支付的最低限额
        if (ArithUtil.mul(selectAmount, 100d) < minAmount) {
            Toast.makeText(mActivity, getString(R.string.min_transfer_scanpay_alert, minAmount / 100), Toast.LENGTH_SHORT).show();
            return;
        }
        // 打开扫描界面扫描条形码或二维码
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
        params.put(ZZTongActivity.PAYTYPE, payType);
        params.put("isOpenWechatPayScan", isOpenWechatPayScan);
        mainActivity.startActivityForResult(mainActivity, WebPayWaitingResultActivity.class, params, ZZTConstant.CONNECT_WEB_PAY_CODE);*/
    }

    //弹出正扫支付类型选择对话框
    private void selectPayType() {
        boolean isShowWeChatPayScan = false;
        boolean isShowAliPayScan = false;
        if (isOpenWechatPayScan && isOpenAlipayScan) {
            //显示2个图标
            isShowWeChatPayScan = true;
            isShowAliPayScan = true;
        } else {
            //显示一个图标，居中显示
            if (isOpenWechatPayScan) {
                isShowWeChatPayScan = true;
            } else if (isOpenAlipayScan) {
                isShowAliPayScan = true;
            }
        }
        final ZZTShowDialog payTypeView = new ZZTShowDialog(mainActivity, R.layout.layout_selectpay, R.style.dialog);
        RelativeLayout rela_alipay = (RelativeLayout) payTypeView.getDialog().findViewById(R.id.rela_alipay);
        ImageButton imagebutton_alipay = (ImageButton) payTypeView.getDialog().findViewById(R.id.imagebutton_alipay);
        if (!isShowAliPayScan) {
            rela_alipay.setVisibility(View.GONE);
        }
        RelativeLayout rela_wechatpay = (RelativeLayout) payTypeView.getDialog().findViewById(R.id.rela_wechatpay);
        ImageButton imagebutton_wechatpay = (ImageButton) payTypeView.getDialog().findViewById(R.id.imagebutton_wechatpay);
        if (!isShowWeChatPayScan) {
            rela_wechatpay.setVisibility(View.GONE);
        }
        payTypeView.getDialog().setCancelable(true);
        payTypeView.getDialog().setCanceledOnTouchOutside(true);

        imagebutton_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payTypeView.dismiss();
                go2QrCodePay(8);
            }
        });
        imagebutton_wechatpay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payTypeView.dismiss();
                go2QrCodePay(4);
            }
        });
        payTypeView.show();
    }

    //去正扫支付
    private void go2QrCodePay(int type) {
        double currentMiniPayAmount = 0d;
        if (type == 4) {
            currentMiniPayAmount = wechatScanpayAmount;
        } else if (type == 8) {
            currentMiniPayAmount = aliScanpayAmount;
        }
        if (ArithUtil.mul(selectAmount, 100d) < currentMiniPayAmount) {
            Toast.makeText(mActivity, getString(R.string.min_transfer_alert, currentMiniPayAmount / 100), Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
        intent.putExtra("isFromReceivable", true);
//        intent.putExtra("isOpenWechatPayScan",isOpenWechatPayScan?1:0);
//        intent.putExtra("isOpenAlipayScan",isOpenAlipayScan?1:0);
        intent.putExtra("qrcodeType", type);
        intent.setClass(mainActivity, QRCodeReceiptActivity.class);
        startActivity(intent);
    }

    private void doOKClickNoCardPay() {
        if (!mainActivity.requestCurrentLocation(true)) {
            return;
        }
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        selectAmount = Double.valueOf(mMoneyText);
        //扫码支付的最低限额
        double minAmount = noCardPayAmount;
        if (ArithUtil.mul(selectAmount, 100d) < minAmount) {
            Toast.makeText(mActivity, getString(R.string.min_no_card_pay_alert, minAmount / 100), Toast.LENGTH_SHORT).show();
            return;
        }
        params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
        mainActivity.startActivity(mainActivity, NoCardPayActivity.class, params);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_WEBPAY) {
                doOKClickWebPay();
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY) {
                doOKClickBankCardPay();
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_NO_CARD_PAY) {
                HPLog.i(HPLog.YL_TAG, "rf_no_card_pay_btn PermissionListener:Success");
                doOKClickNoCardPay();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_WEBPAY) {
                HPLog.i(HPLog.YL_TAG, "rf_no_card_pay_btn PermissionListener:Failed");
                Toast.makeText(mActivity, R.string.message_webpay_permission_failed, Toast.LENGTH_SHORT).show();
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY) {
                Toast.makeText(mActivity, R.string.message_bankpay_permission_failed, Toast.LENGTH_SHORT).show();
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_NO_CARD_PAY) {
                Toast.makeText(mActivity, R.string.message_location_failed, Toast.LENGTH_SHORT).show();
            }

            if (AndPermission.hasAlwaysDeniedPermission(mainActivity, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mainActivity, PermissionRequestCode.REQUEST_CODE_SETTING).show();
            }
        }
    };

    /***
     * 进入微信正扫界面
     * 获取商户二维码
     *
     * @param payType 支付方式
     * @deprecated 微信正扫换成了现在的扫码支付，客户端不区分支付宝和微信 use{@link com.handpay.zztong.hp.ScannerCodePayActivity} instead
     */
    @Deprecated
    public void doWetchatScanner(int payType) {
        if (!mainActivity.requestCurrentLocation(true)) {
            return;
        }
        String content = mInputMoneyet.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        selectAmount = Double.valueOf(mMoneyText);
        if (ArithUtil.mul(selectAmount, 100d) < wechatScanpayAmount) {
            Toast.makeText(mActivity, getString((payType == PAY_TYPE_ALIPAY ? R.string.min_transfer_alipay_alert : R.string.min_transfer_wechatpay_alert), wechatScanpayAmount / 100), Toast.LENGTH_SHORT).show();
            return;
        }
        SwiperUtils.cleanSwiperData();
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("amount", SecureManager.getInstance().des(BigDecimal.valueOf(ArithUtil.mul(selectAmount, 100d)).toPlainString(), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("tradeType", payType + "");
        params.put("clientVersion", "v" + ClientEngine.VERSION);
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_ADDRESS, address);
        mainActivity.doPost(mainActivity, ZZTongActivity.Do_QrCodeTransfer, params, true);
    }

    private void getAreaTradeValue() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        mainActivity.doJsonPost(true, mainActivity, ZZTongActivity.Do_GetAreaTradeValue, TradeAreaBean.class, params, true, true);
    }

    private void getMuiltRate(double amount) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("businessType", "1");
        params.put("amount", SecureManager.getInstance().des(ArithUtil.mul(selectAmount, 100d) + "", 1, null));
        mainActivity.doJsonPost(true, mainActivity, ZZTongActivity.Do_ZztRateList, RateList.class, params, true, true);
    }

    private Hashtable<String, String> treatParams() {
        Hashtable<String, String> params = new Hashtable<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
        return params;
    }

    @Override
    public void onVPOS() {
        super.onVPOS();
        HPLog.i(HPLog.FDL_TAG, "Receivablefragment onVPOS");
        mainActivity.setMode(SwiperMode.NORMAL_TRANS, false, new Runnable() {
            @Override
            public void run() {
                goTo_VPOS_Activity();
            }
        });
    }

    public void goTo_VPOS_Activity() {
        HPLog.i(HPLog.FDL_TAG, "Receivablefragment goTo_VPOS_Activity---run 1");
        if (mainActivity.checkVPOS(mainActivity, true)) {
            HPLog.i(HPLog.FDL_TAG, "Receivablefragment goTo_VPOS_Activity---run 2");
            if (Address.IS_CHECK_ADDRESS && !mainActivity.showNoTranctionMsg()) {
                HPLog.i(HPLog.FDL_TAG, "不在交易范围之内");
                return;
            }
            HPLog.i(HPLog.FDL_TAG, "Receivablefragment goTo_VPOS_Activity---run 3");
            Hashtable<String, Object> params = new Hashtable<String, Object>();
            params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
            params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
            params.put("isRateNull", rates.isRateNull());
            if (!rates.isRateNull() && currentSelectRate != null) {
                HPLog.i(HPLog.TAG_RESULT, "rates:" + rates.toString());
                params.put("selectedRate", currentSelectRate.getRateCodeId());
                params.put("isPublicCharge", currentSelectRate.getIsPublicChargeId());
            }
            mainActivity.startActivity(mainActivity, VPOSActivity.class, params);
            currentSelectRate = null;
            // 跳转界面之前，清空金额
            restZero();
        }
    }

    public void goToVPOSActivity() {
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        params.put(VPOSActivity.Transfer_Amount_Key, selectAmount * 100);
        params.put("isRateNull", rates.isRateNull());
        mainActivity.startActivity(mainActivity, VPOSActivity.class, params);
        // 跳转界面之前，清空金额
        restZero();
    }

    public void onOkClick(Dialog dialog, Rate obj) {
        HPLog.i(HPLog.TAG_RESULT, obj != null ? obj.toString() : "Error：Rate 对象为null！");
        String temp = obj != null ? obj.getRateAmount() : null;
        if (TextUtils.isEmpty(temp)) {
            Toast.makeText(getActivity(), mainActivity.getString(R.string.hint_data_exception), Toast.LENGTH_LONG).show();
            return;
        }
        dialog.cancel();
        //如果大于0 则继续判断金额
        if (CommonUtils.objectToInt(temp) > 0 && (selectAmount * 100) > Double.parseDouble(temp)) {

            mainActivity.showAlertDialog(mainActivity, mainActivity.getString(R.string.tip), mainActivity.getString(R.string.hint_limit_money_no_point, (Double.parseDouble(temp) / 100)), true, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            return;
        }
        currentSelectRate = obj;
        onVPOS();
    }
}
